package example.com.zcq.mymj.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import java.util.HashMap;
import java.util.Map;

import example.com.zcq.mymj.R;
import example.com.zcq.mymj.bean.KaiGuan;
import example.com.zcq.mymj.net.HttpInterface;
import example.com.zcq.mymj.net.RetrofitHttp;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class SplashActivity extends AppCompatActivity {
    private static final int sleepTime = 1000;
    private SharedPreferences sharedPreferences;
    public static final String firstLogin = "firstLogin";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        sharedPreferences = getSharedPreferences("sys_info", MODE_PRIVATE);
    }

    @Override
    protected void onResume() {
        super.onResume();
//        requestWebKG();


        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                go();
            }
        }, sleepTime);
    }

    private void requestWebKG() {
        Map<String, String> hashMap = new HashMap<>();
//        hashMap.put("appid", "zxcv123");
        hashMap.put("appid", "bbb001");


        HttpInterface h = RetrofitHttp.getSimpleRetrofit();
        h.webkaiguan(hashMap).enqueue(new Callback<KaiGuan>() {
            @Override
            public void onResponse(Call<KaiGuan> call, Response<KaiGuan> response) {
                KaiGuan bean = response.body();

                if (bean != null) {
                    int status = bean.getStatus();
                    //              state     应用的状态：0 不跳转，1跳转'
                    if (status == 1) {
                        startActivity(new Intent(SplashActivity.this, WebMJActivity.class)
                                .putExtra("mjurl", "http://www.xiexingcun.com/Poetry.html"));
                        finish();
                    } else {
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                go();
                            }
                        }, sleepTime);
                    }

                }
            }

            @Override
            public void onFailure(Call<KaiGuan> call, Throwable t) {

            }
        });

    }

    private void go() {
        if (sharedPreferences.getBoolean(firstLogin, true)) {
            sharedPreferences.edit().putBoolean(firstLogin, false).commit();
            startActivity(new Intent(this, GuideActivity.class));
        } else {
            startActivity(new Intent(this, MainActivity.class));
        }
        finish();

    }
}
